package co.fitstart.admin.web.controller.user;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.admin.service.InbodyRecordService;
import co.fitstart.entity.user.inbody.InbodyData;

/**
 *
 * @author lidan
 *
 */
@Controller
@RequestMapping("inbody-uploads")
public class InbodyUploadController {

    private static final Logger logger = LoggerFactory.getLogger(InbodyUploadController.class);

    @Autowired
    private InbodyRecordService inbodyRecordService;


    /**
     * Post inbody json data
     *
     * @param inbodys
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onUpload(@RequestBody String inbodys){


        Result result = new Result();

        try {

            logger.info("onUpload() -- with data:::", inbodys);

            JSONObject responseObject = JSON.parseObject(inbodys);

            JSONArray data = responseObject.getJSONArray("inbodyData");

            for(int i = 0; i < data.size(); i++) {
                try {

                    InbodyData inbodyData = data.getObject(i, InbodyData.class);

                    logger.info("##onUpload - inbody record get inbodyData." + data.get(i).toString());

                    inbodyRecordService.uploadInbodyData(inbodyData);

                    result.success().message("##onUpload -- this data compelete");

                } catch (Exception e) {

                    logger.info("##onUpload -- this data item can not map inbodyData", i);

                }
            }


        } catch (Exception e) {

            logger.error("onUpload() error", e);

            result.fail().message("get inbodys data error");

        }

        return JsonUtils.toJsonString(result);
    }

}
